package com.banciyuan.bcywebview.biz.detail;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.utils.common.UIUtils;

import net.sourceforge.pinyin4j.PinyinHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hy on 2015/8/17.
 */
public class SearchPersonActivity extends BaseActivity implements View.OnClickListener {
    private ArrayList<String> names;
    private ListView lvSearchPerson;
    private EditText etSearch;
    private List<String> searchedNames = new ArrayList<String>();
    private TextView header;
    private SearchPersonAdapter adapter;
    private String nums = "0123456789";
    private boolean search_flag = false;
//    private StringBuffer mFirstNoQwertySearchResultInput = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_searchperson);
        initArgs();
        initUi();
        initAction();
    }

    @Override
    protected void initUi() {
        lvSearchPerson = (ListView) findViewById(R.id.lv_search_person);
        etSearch = (EditText) findViewById(R.id.et_search);
        gethead();
    }

    private void processData() {
        adapter = new SearchPersonAdapter(this, searchedNames);
        lvSearchPerson.setAdapter(adapter);
    }

    @Override
    protected void initArgs() {
        names = getIntent().getStringArrayListExtra("names");
    }

    @Override
    protected void initAction() {

        findViewById(R.id.discover_search_cancel_tv).setOnClickListener(this);

        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

                final String searchWord = editable.toString();
                searchedNames.clear();
                if (null != adapter) {
                    adapter.notifyDataSetChanged();
                }
                if (TextUtils.isEmpty(searchWord)) {
                    header.setText("");
                    header.setVisibility(View.GONE);
                    lvSearchPerson.setDividerHeight(UIUtils.dip2px(0, SearchPersonActivity.this));
                    return;
                }
                final String changedSearchWord = searchWord.toLowerCase();
                if (!TextUtils.isEmpty(changedSearchWord)) {
                    lvSearchPerson.setDividerHeight(UIUtils.dip2px(1, SearchPersonActivity.this));
                    header.setVisibility(View.VISIBLE);
                    header.setText("@" + searchWord);
                    if (!search_flag) {
                        new AsyncTask<Void, Void, List<String>>() {
                            @Override
                            protected List<String> doInBackground(Void... voids) {
                                search_flag = true;
                                return processSearchNames(changedSearchWord);
                            }

                            @Override
                            protected void onPostExecute(List<String> strings) {
                                searchedNames.addAll(strings);
                                search_flag = false;
                                processData();
                                super.onPostExecute(strings);
                            }
                        }.execute();
                    }
                }
            }
        });

        lvSearchPerson.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if (!search_flag) {
                    int index = position - 2;
                    if (index < 0)
                        return;
                    if (!searchedNames.isEmpty()) {
                        String personname = searchedNames.get(index);
                        if (!TextUtils.isEmpty(personname)) {
                            Intent intent = new Intent();
                            intent.putExtra("personname", personname + " ");
                            setResult(RESULT_OK, intent);
                            finish();
                        }
                    }
                }
            }
        });

        header.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String personname = etSearch.getText().toString().trim();
                Intent intent = new Intent();
                intent.putExtra("personname", personname + " ");
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.discover_search_cancel_tv:
                finish();
                break;
        }
    }

    private void gethead() {
        header = new TextView(this);
        AbsListView.LayoutParams params = new AbsListView.LayoutParams(-1, UIUtils.dip2px(40, this));
        header.setBackgroundColor(getResources().getColor(R.color.bg_two));
        header.setGravity(Gravity.CENTER_VERTICAL);
        header.setPadding(UIUtils.dip2px(16, this), 0, 0, 0);
        header.setLayoutParams(params);
        header.setTextColor(getResources().getColor(R.color.mine_textcolor));
        header.setTextSize(17);
        lvSearchPerson.addHeaderView(header);
    }


    private int preSearchLength = 0;
    private List<String> preListNames;

    private List<String> processSearchNames(String changedSearchWord) {
        List<String> templist = new ArrayList<String>();
        int nowSearchLength = changedSearchWord.length();
        List<String> srcNames;
        if (preSearchLength != 0 && (nowSearchLength - preSearchLength) > 0) {
            srcNames = preListNames;
        } else {
            srcNames = names;
        }
        preSearchLength = changedSearchWord.length();
        if (!TextUtils.isEmpty(changedSearchWord)) {
            for (int i = 0; i < srcNames.size(); i++) {
                String name = srcNames.get(i);
                String changedName = name.toLowerCase();
                if (changedName.contains(changedSearchWord)) {
                    templist.add(name);
                } else {
                    char[] chars = changedName.toCharArray();
                    StringBuilder sb = new StringBuilder();
                    List<Integer> pos = new ArrayList<Integer>();
                    List<String> chList = new ArrayList<String>();
                    StringBuilder firstSb = new StringBuilder();
                    for (int j = 0; j < chars.length; j++) {
                        String[] ch = PinyinHelper.toHanyuPinyinStringArray(chars[j]);
                        if (null != ch) {
                            String key;
                            key = ch[0].substring(0, ch[0].length() - 1);
                            pos.add(sb.length());
                            chList.add(key);
                            sb.append(key);
                            if (key.length() > 0)
                                firstSb.append(key.charAt(0));
                        }
                    }
                    if (templist.contains(name))
                        continue;
                    String src = sb.toString();
                    if (src.contains(changedSearchWord)) {
                        int innerIndex = src.indexOf(changedSearchWord);
                        if (pos.contains(innerIndex) && !templist.contains(name)) {
                            templist.add(name);
                            continue;
                        }
                    }
                    String firstSbStr = firstSb.toString();
                    if (firstSbStr.contains(changedSearchWord) && !templist.contains(name)) {
                        templist.add(name);
                        continue;
                    }
                    String str = "";
                    for (int j = 0; j < firstSbStr.length(); j++) {
                        if (j < firstSbStr.length() - 1) {
                            str += chList.get(j);
                            String testStr = str + firstSbStr.substring(j + 1, firstSbStr.length());
                            if (testStr.startsWith(changedSearchWord) && !templist.contains(name)) {
                                templist.add(name);
                                break;
                            }
                        }
                    }
                }
            }
        }
        preListNames = templist;
        return templist;
    }
}
